<?php

require_once 'init.php';
require_once 'shop_common.php';


$product = new Product($par->get('productId'));
$smarty->assign('product',$product);

$manufacturer = new Manufacturer($product->manufacturerId());
$smarty->assign('manufacturer',$manufacturer);

$title = $descr = $keywords = (string)$product;

$groupId = null;
$productGroups = new ProductGroups($product->id());
if (!$productGroups->is_empty()) {
   $groupId = $productGroups->getIterator()->current()->id();
}

$smarty->assign('wholesalePrice', new ProductAttribute('wholesale_price',$product->id()));

$crumbs = array();
if ($groupId) {
	$crumbs = groupToCrumbs(new Group($groupId));
}

$options = new ProductOptions($product->id());
$smarty->assign('options', $options->toArray());

$optionsWholesalePrices = array();

foreach ($options as $option)
{
	$optionsWholesalePrices[] = new ProductOptionAttribute('wholesale_price',$option->id());
}
$smarty->assign('optionsWholesalePrices', $optionsWholesalePrices);

$smarty->assign('productImages',$product->images());


$attributes = array();  //array(option name, array(attributes))


function isAttributeNullForAll($iAttr)
{
	global $attributes;
	foreach ($attributes as $attrsForOption) 
	{
		if (!$attrsForOption[1][$iAttr]->isNull()) {
			return false;
		}

	}
	return true;
}

function remAttributeInAll($iAttr)
{
	global $attributes;
		
	for ($i=0; $i<count($attributes); ++$i) 
	{
		array_splice($attributes[$i][1], $iAttr, 1);
	}
}

function remNullAttributes()
{
	global $attributes;
	
	if (empty($attributes)) {
		return;
	}

	$numOfAttrs = count($attributes[0][1]);
	for ($i=0; $i<$numOfAttrs; ++$i) 
	{
		if (isAttributeNullForAll($i)) {
			remAttributeInAll($i);
			--$i;
			$numOfAttrs = count($attributes[0][1]);
		}
	}
}

function fillAttributes($groupId)
{
	global $product, $options, $attributes;
	
	$attributesOb = 
		$groupId ? 
			new ProductGroupAttributes($product->id(), $groupId) :
			new ProductAttributes($product->id());
			
	if (!$attributesOb->allNull()) {
		$attributes[] = array( $product->name(), $attributesOb->toArray() );		//treat product like option
	}
	
	foreach ($options as $option) 
	{
		$attributesOb = 
			$groupId ? 
				new ProductOptionGroupAttributes($option->id(), $groupId) :
				new ProductOptionAttributes($option->id(), $groupId);

		if (!$attributesOb->allNull()) {
			$attributes[] = array( $option->name(), $attributesOb->toArray() );
		}
	}
	
	remNullAttributes();
}

fillAttributes(null);
$smarty->assign('attributes',$attributes);

$attrNames = array();
if (!empty($attributes)) 
{
	foreach ($attributes[0][1] as $attr) {
		$attrNames[] = $attr->name();
	}
}
$smarty->assign('attrNames',$attrNames);

$relatedProducts = new RelatedProducts($product->id());
$smarty->assign('related', $relatedProducts->getList());

show('product', $title, $crumbs);

?>